package com.cn.admin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cn.admin.entity.User;
import com.cn.admin.entity.UserQuery;
import com.cn.admin.exception.CustomException;
import com.cn.admin.node.MenuNode;
import com.cn.admin.service.MenuRoleService;
import com.cn.admin.service.MenuService;
import com.cn.admin.service.UserService;
import com.cn.admin.thread.MusicThread;
import com.cn.admin.utils.FTPUtils;
import com.cn.admin.utils.HttpUtils;
import com.cn.admin.utils.JwtUtils;
import com.cn.admin.utils.WebUtils;
import com.cn.admin.vo.ResponseObject;
import com.cn.admin.vo.ResponseUserToken;
import com.cn.admin.vo.ResultCode;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/admin")
public class LoginController {

    private static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private MenuRoleService menuRoleService;

    @Autowired
    private JwtUtils jwtTokenUtil;

    @PostMapping("/user/login")
    public ResponseObject<Object> login(HttpServletRequest request, String username,String password){

        logger.info("username={},password={},id={}",username,password);

        String remoteIp = WebUtils.getRemoteIp(request);
        System.out.println("================"+remoteIp);

        ResponseUserToken login = userService.login(username, password);
        String token = login.getToken();

        return  ResponseObject.success(token);

    }



    @GetMapping("/user/info")
    public Object info(String token){

        Map map = new HashMap();
        List<Long> roleList =new ArrayList<>();
        roleList.add(1L);
        roleList.add(2L);

        map.put("name","22");
        map.put("role","admin");
        map.put("roles",roleList);

        //查询菜单列表
        List menus = menuRoleService.getMenusByRoleIds(roleList);
        map.put("menus",menus);

        //获取用户可以操作的菜单列表
        List<MenuNode> menuNodes =  menuRoleService.getMenusTreeByRoleIds(roleList);
        //返回（根据拥有操作权限的菜单列表构造）路由信息
        map.put("routers",generateRouters(menuNodes));
        //返回所有可操作的功能列表，用作进行按钮级别权限控制
        map.put("permissions",generatePermissions(roleList));


        logger.info("222222222222222222========="+token);

        return ResponseObject.success(map);

    }


    @PostMapping("/user/logout")
    public Object logout(){

        return ResponseObject.success("");

    }

    private List<Map> generateRouters(List<MenuNode> list){
        List<Map> result = new ArrayList<>();
        for(MenuNode menuNode:list){
            Map map = new HashMap();
            map.put("path",menuNode.getUrl());
            map.put("component","Layout");
            map.put("redirect","#");
            map.put("name",menuNode.getName());
            map.put("alwaysShow",true);
            List<Map> children = new ArrayList<>();
            if(!menuNode.getChildren().isEmpty()){
                for(MenuNode child:menuNode.getChildren()) {
                    if(child.getIsmenu().intValue() != 1){
                        continue;
                    }
                    Map map1 = new HashMap();
                    map1.put("path", child.getUrl());
                    map1.put("name", child.getName());
                    Map m=new HashMap();
                    map1.put("meta", m.put("title",child.getName()));
                    children.add(map1);
                }
                map.put("children",children);
            }
            result.add(map);
        }
        return result;
    }


    private List<String> generatePermissions(List<Long> roleList) {
        Set<String> permissionSet = new HashSet<>();
        for (Long roleId : roleList) {
            List<String> permissions =     menuService.getResUrlsByRoleId(roleId.intValue());
            if (permissions != null) {
                for (String permission : permissions) {
                    if (StringUtils.isNotEmpty(permission)) {
                        permissionSet.add(permission);
                    }
                }
            }
        }
        return new ArrayList(permissionSet);
    }







}
